#pragma once

#include <vector>

namespace solution_095
{

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution
{
public:
    std::vector<TreeNode*> generateTrees(int n)
    {
        return n ? build_subtree(1, n) : std::vector<TreeNode*>();
    }

private:
    std::vector<TreeNode*> build_subtree(int left, int right)
    {
        if (left > right)
            return { nullptr };

        std::vector<TreeNode*> trees;
        for (int i = left; i <= right; ++i) {
            auto l_tree = build_subtree(left, i - 1);
            auto r_tree = build_subtree(i + 1, right);
            for (auto l_child : l_tree) {
                for (auto r_child : r_tree)
                    trees.push_back(new TreeNode(i, l_child, r_child));
            }
        }
        return trees;
    }
};

}  /* namespace solution_095 */
